#include "createrole.h"
#include "common.h"
#include "loadscene.h"
#include "startscene.h"
#include "gamescene.h"
#include "player.h"

namespace fireplane
{

#define _MAX_PLANE_COUNT_ (6)
#define _USE_FONT_ "font/LiSu.ttf"
#define _USE_FONT_SIZE_ (25)


	static CCRect LEFT_RECT = CCRectMake(13,6,414,278);
	static CCRect RIGHT_RECT = CCRectMake(433,6,220,284);

	bool CreateRole::init()
	{
		_selectIdx = -1;
		_active_ttf = NULL;

		_createUI();
		_leftclip = BGClipLayer::node();
		_leftclip->setClipRect(LEFT_RECT);
		_rightclip = BGClipLayer::node();
		_rightclip->setClipRect(RIGHT_RECT);
		addChild(_leftclip);
		addChild(_rightclip);

		for (int i = 0;i < _MAX_PLANE_COUNT_;i++)
		{
			_createIntroduce(i,"createrole/longdi.txt");
			_createAttribute(i,"createrole/longdishuxing.txt");
		}
		
		onFocusChange(0);

		setTouchEnabled(true);
		return true;
	}

	cocos2d::CCScene* CreateRole::scene()
	{
		CCScene * scene = NULL;
		do 
		{
			// 'scene' is an autorelease object
			scene = CCScene::create();
			CC_BREAK_IF(! scene);

			CCNode* parentNode = Common::createScaleNode(scene);
			// 'layer' is an autorelease object
			CreateRole *layer = CreateRole::node();
			CC_BREAK_IF(! layer);

			// add layer as a child to scene
			parentNode->addChild(layer);
		} while (0);

		// return the scene
		return scene;
	}

	static int _load_idx = 0;
	static const char* const _all_load_res[] = 
	{
		"createrole/createrole.plist",
	};

	bool CreateRole::loadRes( void )
	{
		int count = sizeof(_all_load_res) / sizeof(_all_load_res[0]);

		if (_load_idx == count)
		{
			CCDirector::sharedDirector()->replaceScene(CreateRole::scene());
			_load_idx = 0;
			return true;
		}
		else
		{
			string fileName = _all_load_res[_load_idx];

			Common::doLoadLogic(fileName);

			_load_idx++;
			return false;
		}
	}

	void CreateRole::onStartGame(CCObject* pSender)
	{
		LoadingScene::registerLoadFunction(&(GameScene::loadRes));
		CCScene *pScene = LoadingScene::scene();
		CCDirector::sharedDirector()->replaceScene(pScene);
	}

	void CreateRole::onClickPlane(CCObject* pSender)
	{
		CCMenuItemSprite* item = (CCMenuItemSprite*)pSender;
		onFocusChange(item->getTag());
	}

	static const char* const _all_plane[] =
	{
		"longhao.png",
		"lockselect.png",
		"lockselect.png",
		"lockselect.png",
		"lockselect.png",
		"lockselect.png",
	};

	void CreateRole::_createUI()
	{
		CCSize winSize = Common::getWinSize();

		CCSprite* createRoleBG = CCSprite::create("createrole/bg.jpg");
		createRoleBG->setPosition(ccp(winSize.width / 2,winSize.height / 2));
		addChild(createRoleBG);
		createRoleBG->runAction(
			CCRepeatForever::create((CCActionInterval*)
			CCSequence::create(
			CCTintTo::create(
			2.0f,32,32,32),
			CCTintTo::create(
			2.0f,255,255,255),
			NULL)));


		CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
		CCSpriteFrame* frame = cache->spriteFrameByName("intro.png");
		CCSprite* intro = CCSprite::createWithSpriteFrame(frame);
		
		intro->setPosition(ccp(winSize.width / 2,intro->getContentSize().height / 2));
		addChild(intro);

		CCMenu* menu = CCMenu::create();
		menu->setPosition(ccp(0,0));
		addChild(menu);

		CCPoint pos;
		for (int i = 0;i < _MAX_PLANE_COUNT_;i++)
		{
			_plane_items[i] = Common::itemFromNormalImage(_all_plane[i],_all_plane[i],
				this,menu_selector(CreateRole::onClickPlane),false);
			menu->addChild(_plane_items[i],0);
			_plane_items[i]->setPosition(ccp(_plane_items[i]->getContentSize().width / 2 + _plane_items[i]->getContentSize().width * i,
				 _plane_items[i]->getContentSize().height / 2 + intro->getContentSize().height));
			_plane_items[i]->setTag(i);

			if (i == 0)
			{
				pos = _plane_items[i]->getPosition();
			}
		}

		_select = Common::createSpriteByFrameName("selectkuang.png");
		addChild(_select);
		_select->setPosition(pos);
		_select->runAction(
			CCRepeatForever::create((CCActionInterval*)
			CCSequence::create(
			CCTintTo::create(
			0.5f,128,128,128),
			CCTintTo::create(
			0.5f,255,255,255),
			NULL)));


		CCMenuItemSprite* startGame = Common::itemFromNormalImage("startgame.png","startgame.png",
			this,menu_selector(CreateRole::onStartGame),false);
		((CCSprite*)startGame->getNormalImage())->setColor(ccc3(200,200,200));

		menu->addChild(startGame,0);
		startGame->setPosition(ccp(winSize.width / 2,_select->getPosition().y + 
			_select->getContentSize().height / 2 + startGame->getContentSize().height / 2));

		CCMenuItemSprite* backGame = Common::itemFromNormalImage("backmenu.png","backmenu.png",
			this,menu_selector(CreateRole::onBackMenu),false);
		((CCSprite*)backGame->getNormalImage())->setColor(ccc3(200,200,200));
		menu->addChild(backGame,0);
		backGame->setPosition(ccp(backGame->getContentSize().width / 2,
			winSize.height - backGame->getContentSize().height / 2));


		for (int i = 0;i < _MAX_PLANE_COUNT_;i++)
		{
			_all_planes[i] = Common::createSpriteByFrameName("longdihao.png");
			addChild(_all_planes[i]);

			_all_planes[i]->setPosition(ccp(winSize.width / 2 + winSize.width,
				winSize.height - _all_planes[i]->getContentSize().height / 2));
		}
	}

	void CreateRole::_createAttribute(int idx,const char* filename)
	{
		CCSize textRect = RIGHT_RECT.size;
		textRect.height = 0;

		unsigned long size;
		unsigned char* buffer = CCFileUtils::sharedFileUtils()->getFileData(filename,"rb",&size);
		unsigned char* showBuffer = new unsigned char[size + 1];
		memcpy(showBuffer,buffer,size);
		showBuffer[size] = 0;

		_all_planes_attribute[idx] = 
			CCLabelTTF::create((char*)showBuffer,_USE_FONT_,_USE_FONT_SIZE_,textRect,kCCTextAlignmentLeft);
		_rightclip->addChild(_all_planes_attribute[idx]);
		_all_planes_attribute[idx]->setAnchorPoint(ccp(0,1.0f));
		_all_planes_attribute[idx]->setPosition(ccp(440,284));

		_all_planes_attribute_startpos[idx] = _all_planes_attribute[idx]->getPosition();

		delete[] buffer;
		delete[] showBuffer;
	}

	void CreateRole::_createIntroduce(int idx,const char* filename)
	{
		CCSize textRect = LEFT_RECT.size;
		textRect.height = 0;

		unsigned long size;
		unsigned char* buffer = CCFileUtils::sharedFileUtils()->getFileData(filename,"rb",&size);
		unsigned char* showBuffer = new unsigned char[size + 1];
		memcpy(showBuffer,buffer,size);
		showBuffer[size] = 0;

		_all_planes_intro[idx] = 
			CCLabelTTF::create((char*)showBuffer,_USE_FONT_,_USE_FONT_SIZE_,textRect,kCCTextAlignmentLeft);
		_leftclip->addChild(_all_planes_intro[idx]);
		_all_planes_intro[idx]->setAnchorPoint(ccp(0,1.0f));
		_all_planes_intro[idx]->setPosition(ccp(20,286));

		_all_planes_intro_startpos[idx] = _all_planes_intro[idx]->getPosition();
	
		delete[] buffer;
		delete[] showBuffer;
	}

	void CreateRole::onBackMenu(CCObject* pSender)
	{
		LoadingScene::registerLoadFunction(&(StartScene::loadRes));
		CCScene *pScene = LoadingScene::scene();
		CCDirector::sharedDirector()->replaceScene(pScene);
	}

	void CreateRole::registerWithTouchDispatcher()
	{
		CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,-128+1,true);
	}

	void CreateRole::onFocusChange(int idx)
	{
		CCSize winsize = Common::getWinSize();
		_select->runAction(CCMoveTo::create(0.2f,_plane_items[idx]->getPosition()));

		_all_planes[idx]->runAction(
			CCMoveTo::create(0.5f,ccp(winsize.width / 2,
			_all_planes[idx]->getPosition().y)));

		if (_selectIdx != -1)
		{
			_all_planes[_selectIdx]->runAction(CCMoveTo::create(0.5f,ccp(winsize.width / 2 + winsize.width,
				_all_planes[_selectIdx]->getPosition().y)));
		}

		_selectIdx = idx;

		for (int i = 0;i < _MAX_PLANE_COUNT_;i++)
		{
			if (_selectIdx == i)
			{
				_all_planes_intro[i]->setVisible(true);
				_all_planes_attribute[i]->setVisible(true);
			}
			else
			{
				_all_planes_intro[i]->setVisible(false);
				_all_planes_attribute[i]->setVisible(false);
			}
		}
	}

	bool CreateRole::ccTouchBegan( CCTouch *pTouch, CCEvent *pEvent )
	{
		CCPoint pos = pTouch->getLocationInView();
		pos = CCDirector::sharedDirector()->convertToGL(pos);
		pos = this->getParent()->convertToNodeSpace(pos);

		
		if (LEFT_RECT.containsPoint(pos))
		{
			_beginPos = pos;
			_active_ttf = _all_planes_intro[_selectIdx];
			_active_pos = _all_planes_intro_startpos;

			return true;
		}
		else if(RIGHT_RECT.containsPoint(pos))
		{
			_beginPos = pos;
			_active_ttf = _all_planes_attribute[_selectIdx];
			_active_pos = _all_planes_attribute_startpos;

			return true;
		}
		return false;
	}

	void CreateRole::ccTouchMoved( CCTouch *pTouch, CCEvent *pEvent )
	{
		CCPoint pos = pTouch->getLocationInView();
		pos = CCDirector::sharedDirector()->convertToGL(pos);
		pos = this->getParent()->convertToNodeSpace(pos);
		float dy = pos.y - _beginPos.y;

		CCPoint curpos = _active_ttf->getPosition();
		curpos.y += dy;

		if (curpos.y < _active_pos[_selectIdx].y)
		{
			curpos.y = _active_pos[_selectIdx].y;
		}
		else if (curpos.y > _active_pos[_selectIdx].y +
			_active_ttf->getContentSize().height * 0.8f)
		{
			curpos.y = _active_pos[_selectIdx].y +_active_ttf->getContentSize().height * 0.8f;
		}

		_active_ttf->setPosition(curpos);
		_beginPos = pos;
	}

	void CreateRole::ccTouchEnded( CCTouch *pTouch, CCEvent *pEvent )
	{
		_active_ttf = NULL;
	}

}